//
//  NSString+SWExtension.m
//  TeaMall
//
//  Created by Mac on 2018/3/29.
//  Copyright © 2018年 TM. All rights reserved.
//

#import "NSString+SWExtension.h"
#import <objc/runtime.h>
#import <CommonCrypto/CommonDigest.h>

#import <ifaddrs.h>
#import <arpa/inet.h>

@implementation NSString (SWExtension)
//计算字符串的CGSize
- (CGSize)sw_sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    CGSize resultSize;
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:@selector(boundingRectWithSize:options:attributes:context:)];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:self];
        [invocation setSelector:@selector(boundingRectWithSize:options:attributes:context:)];
        NSDictionary *attributes = @{ NSFontAttributeName:font };
        NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin;
        NSStringDrawingContext *context;
        [invocation setArgument:&size atIndex:2];
        [invocation setArgument:&options atIndex:3];
        [invocation setArgument:&attributes atIndex:4];
        [invocation setArgument:&context atIndex:5];
        [invocation invoke];
        CGRect rect;
        [invocation getReturnValue:&rect];
        resultSize = rect.size;
    } else {
        NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:@selector(sizeWithFont:constrainedToSize:)];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:self];
        [invocation setSelector:@selector(sizeWithFont:constrainedToSize:)];
        [invocation setArgument:&font atIndex:2];
        [invocation setArgument:&size atIndex:3];
        [invocation invoke];
        [invocation getReturnValue:&resultSize];
    }
    
    return resultSize;
}

- (CGSize)textSizeWithContentSize:(CGSize)size font:(UIFont *)font {
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil].size;
}

/*
 科学计数法，保留n个有效值
 */

-(NSString *) toExponent:(double)d rms:(NSInteger)n
{
    if(n==0)
    {
        return nil;
    }
    //科学计算法 一般写法4.232E这种样式 这里的n代表所有数字的个数 所以这里n++
    n++;
    //判断小数的位数是否超过设定的n的值 如果超过了保留n位有效数字 如果不超过则保留默认小数位数
    //先将double转换成字符串
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSString *dbStr = [formatter stringFromNumber:[NSDecimalNumber numberWithDouble:d]];
    NSInteger length = dbStr.length;
    if ([dbStr containsString:@"."]) {
        length = dbStr.length - 1;
    }
    if (length < n) {
        n = length;
    }
    
    CFLocaleRef currentLocale = CFLocaleCopyCurrent();
    CFNumberFormatterRef customCurrencyFormatter = CFNumberFormatterCreate
    (NULL, currentLocale, kCFNumberFormatterCurrencyStyle);
    NSString *s_n = @"#";
    if(n > 1)
    {
        for(int j = 0; j < n; j++)
        {
            NSString *temp = s_n;
            if(j == 0)
            {
                s_n = [temp stringByAppendingString:@"."];
            }
            else
            {
                s_n = [temp stringByAppendingString:@"0"];
            }
            
        }
        
    }
    CFNumberFormatterSetFormat(customCurrencyFormatter, (CFStringRef)s_n);
    
    double i=1;
    int exponent = 0;
    while (1) {
        i = i*10;
        if(d < i)
        {
            break;
        }
        exponent++;
    }
    double n1 = d * 10 / i;
    
    CFNumberRef number1 = CFNumberCreate(NULL, kCFNumberDoubleType, &n1);
    CFStringRef string1 = CFNumberFormatterCreateStringWithNumber
    (NULL, customCurrencyFormatter, number1);
    NSLog(@"%@", (__bridge NSString *)string1);
    
    NSString * result = [NSString stringWithFormat:@"%@e%d",(__bridge NSString *)string1,exponent];
    
    CFRelease(currentLocale);
    CFRelease(customCurrencyFormatter);
    CFRelease(number1);
    CFRelease(string1);
    
    return result;
}


+(NSString *)getIPAddress {
//    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
//    NSData *data = [NSData dataWithContentsOfURL:ipURL];
//    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
//
//    NSString *ipStr = nil;
//    if (ipDic && [[NSString stringWithFormat:@"%@",ipDic[@"code"]] isEqualToString:@"0"]) { //获取成功
//        ipStr = ipDic[@"data"][@"ip"];
//    }
//    DDLog(@"ipStr=%@",ipStr);
    return @"";
}

// 获取设备IP地址
//// 获取设备IP地址
//+(NSString *)getIPAddress {
//    NSString *address = @"error";
//    struct ifaddrs *interfaces = NULL;
//    struct ifaddrs *temp_addr = NULL;
//    int success = 0;
//    // 检索当前接口,在成功时,返回0
//    success = getifaddrs(&interfaces);
//    if (success == 0) {
//        // 循环链表的接口
//        temp_addr = interfaces;
//        while(temp_addr != NULL) {
//            if(temp_addr->ifa_addr->sa_family == AF_INET) {
//                // 检查接口是否en0 wifi连接在iPhone上
//                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
//                    // 得到NSString从C字符串
//                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
//                }
//                DDLog(@"%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
//            }
//            temp_addr = temp_addr->ifa_next;
//        }
//    }
//    // 释放内存
//    freeifaddrs(interfaces);
//}

@end
